package com.jun.config.shiro;

import com.jun.entity.Admin;
import com.jun.serviceimpl.AdminServiceImpl;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author zjp
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    AdminServiceImpl adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取主身份
        Object user = principalCollection.getPrimaryPrincipal();
        String permissions = user.getClass().getSimpleName();
        //创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission(permissions);  //给用户授权
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if(null != token){
            Admin admin = adminService.getUserById(token.getUsername());
            if(null == admin){
                return null;    //用户名不存在的异常
            }
            String password = admin.getPassword();   //获取用户密码
            return new SimpleAuthenticationInfo(admin,password,"");  //密码认证shiro
        }

        return null;
    }
}
